<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>获取用户位置</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin: 10px 0;
        }
        button:hover {
            background-color: #0056b3;
        }
        button:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        .info {
            margin-top: 20px;
            padding: 15px;
            background-color: #e9ecef;
            border-radius: 5px;
            display: none;
        }
        .error {
            color: #dc3545;
            background-color: #f8d7da;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
            display: none;
        }
        .success {
            color: #155724;
            background-color: #d4edda;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
            display: none;
        }
        .coordinates {
            font-family: monospace;
            background-color: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>获取用户精确位置</h1>
    <p>点击下方按钮获取您的地理位置信息</p>

    <button id="getLocationBtn">获取我的位置</button>

    <div id="error" class="error"></div>
    <div id="success" class="success"></div>

    <div id="locationInfo" class="info">
        <h3>位置信息:</h3>
        <div class="coordinates">
            <p><strong>纬度:</strong> <span id="latitude"></span></p>
            <p><strong>经度:</strong> <span id="longitude"></span></p>
            <p><strong>精度:</strong> <span id="accuracy"></span> 米</p>
            <p><strong>海拔:</strong> <span id="altitude"></span> 米</p>
            <p><strong>方向:</strong> <span id="heading"></span> 度</p>
            <p><strong>速度:</strong> <span id="speed"></span> 米/秒</p>
            <p><strong>时间戳:</strong> <span id="timestamp"></span></p>
        </div>

        <div id="mapContainer" style="margin-top: 20px;">
            <h4>地图位置:</h4>
            <div id="map" style="height: 300px; width: 100%; background-color: #e9ecef; border-radius: 5px; display: flex; align-items: center; justify-content: center;">
                <p>地图加载中...</p>
            </div>
        </div>
    </div>
</div>

<script>
    document.getElementById('getLocationBtn').addEventListener('click', getLocation);

    function getLocation() {
        const btn = document.getElementById('getLocationBtn');
        const errorDiv = document.getElementById('error');
        const successDiv = document.getElementById('success');
        const infoDiv = document.getElementById('locationInfo');

        // 重置显示
        errorDiv.style.display = 'none';
        successDiv.style.display = 'none';
        infoDiv.style.display = 'none';
        btn.disabled = true;
        btn.textContent = '获取中...';

        if (!navigator.geolocation) {
            showError('您的浏览器不支持地理位置服务');
            btn.disabled = false;
            btn.textContent = '获取我的位置';
            return;
        }

        const options = {
            enableHighAccuracy: true,    // 高精度模式
            timeout: 10000,              // 10秒超时
            maximumAge: 60000            // 缓存1分钟
        };

        navigator.geolocation.getCurrentPosition(
            function(position) {
                // 成功获取位置
                displayLocationInfo(position);
                sendToServer(position);
                btn.disabled = false;
                btn.textContent = '获取我的位置';
            },
            function(error) {
                // 获取位置失败
                handleLocationError(error);
                btn.disabled = false;
                btn.textContent = '获取我的位置';
            },
            options
        );
    }

    function displayLocationInfo(position) {
        const coords = position.coords;
        const timestamp = new Date(position.timestamp).toLocaleString();

        // 更新页面显示
        document.getElementById('latitude').textContent = coords.latitude.toFixed(6);
        document.getElementById('longitude').textContent = coords.longitude.toFixed(6);
        document.getElementById('accuracy').textContent = coords.accuracy ? coords.accuracy.toFixed(2) : '未知';
        document.getElementById('altitude').textContent = coords.altitude ? coords.altitude.toFixed(2) : '未知';
        document.getElementById('heading').textContent = coords.heading ? coords.heading.toFixed(2) : '未知';
        document.getElementById('speed').textContent = coords.speed ? coords.speed.toFixed(2) : '未知';
        document.getElementById('timestamp').textContent = timestamp;

        // 显示位置信息区域
        document.getElementById('locationInfo').style.display = 'block';

        // 显示地图（使用百度地图API）
        showMap(coords.latitude, coords.longitude);
    }

    function showMap(lat, lng) {
        const mapDiv = document.getElementById('map');
        mapDiv.innerHTML = `
                <iframe
                    width="100%"
                    height="300"
                    frameborder="0"
                    scrolling="no"
                    marginheight="0"
                    marginwidth="0"
                    src="https://maps.google.com/maps?q=${lat},${lng}&z=15&output=embed"
                    style="border-radius: 5px;">
                </iframe>
            `;
    }

    function sendToServer(position) {
        const locationData = {
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
            accuracy: position.coords.accuracy,
            altitude: position.coords.altitude,
            altitudeAccuracy: position.coords.altitudeAccuracy,
            heading: position.coords.heading,
            speed: position.coords.speed
        };

        fetch('/api/location/save', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(locationData)
        })
            .then(response => response.text())
            .then(data => {
                document.getElementById('success').textContent = '位置信息已成功发送到服务器';
                document.getElementById('success').style.display = 'block';
            })
            .catch(error => {
                console.error('发送到服务器失败:', error);
                document.getElementById('error').textContent = '发送到服务器失败，但位置信息已获取';
                document.getElementById('error').style.display = 'block';
            });
    }

    function handleLocationError(error) {
        let message = '';
        switch(error.code) {
            case error.PERMISSION_DENIED:
                message = '用户拒绝了位置访问请求';
                break;
            case error.POSITION_UNAVAILABLE:
                message = '无法获取当前位置信息';
                break;
            case error.TIMEOUT:
                message = '获取位置信息超时';
                break;
            default:
                message = '发生未知错误';
                break;
        }
        showError(message);
    }

    function showError(message) {
        const errorDiv = document.getElementById('error');
        errorDiv.textContent = message;
        errorDiv.style.display = 'block';
    }

    // 页面加载时检查地理位置支持
    window.addEventListener('load', function() {
        if (!navigator.geolocation) {
            showError('您的浏览器不支持地理位置服务，请使用现代浏览器如Chrome、Firefox等');
        }
    });
</script>
</body>
</html>